//
//  Downloader.m
//  MobileZIPCodes
//
//  Created by Andreas Schwelling on 06.12.07.
//	http://www.andi.de/zipcodes/
// 
//  Released under the GNU General Public License.
//  See LICENSE for details.
//
//  Use at your own risk.
//

#import "Downloader.h"


@implementation Downloader



+ (id) downloadURL: (NSString *)url to: (NSString *)filename delegate: (id) delegate  {
	
	
	
	return [[Downloader alloc] initWithDownloadURL: url savingToFile: filename delegate: delegate];
	
}



- (id) initWithDownloadURL: (NSString *)u savingToFile: (NSString *)f delegate: (id) a  {
	
	//NSLog(@"Downloader begins: downloading\n\t%@\nto:\n\t%@", u, f);
	
	url = [u retain];
	
	file = [f retain];
	
	app = [a retain];
	
	//NSLog(@"delegate: %@",a);
	
	
	nsurl = [[NSURL URLWithString: u] retain];
	
	failed = finished = NO;
	
	loadercycle = 0;
	
	data = [[NSMutableData dataWithCapacity: 100000] retain];
	
	expectedBytes = loadedBytes = 0;
	
	[nsurl loadResourceDataNotifyingClient: self usingCache: NO];
	
	return self;
	
}



- (float) getProgress {
	
	if (expectedBytes == 0) return 0;
	
	return (float)loadedBytes / (float)expectedBytes;
	
}



- (BOOL) finished {
	
	return finished;
	
}



- (BOOL) failed {
	
	return failed;
	
}


- (void)URL:(NSURL *)sender resourceDataDidBecomeAvailable:(NSData *)newBytes {
	
	//NSLog(@"Downloader got %d bytes", [newBytes length]);
	
	[data appendData: newBytes];
	loadedBytes = [data length];
	
	loadercycle++;
	
	
	[app setUpgradeProgress:(int)[newBytes length]];
	
	
	
}



- (void)URL:(NSURL *)sender resourceDidFailLoadingWithReason:(NSString *)reason{
	
	failed = YES;
	
	finished = YES;
	//NSLog(@"del: %@",app);
	[app downloadFailed];
	
}



- (void)URLResourceDidCancelLoading:(NSURL *)sender{
	
	failed = YES;
	
	finished = YES;
	//NSLog(@"del: %@",app);
	
	[app downloadFailed];
	
}



- (void)URLResourceDidFinishLoading:(NSURL *)sender{
	
	//NSLog(@"Downloader finished");
	
	[data writeToFile: file atomically: NO];
	
	finished = YES;
	
	if (loadedBytes<10240) [app downloadFailed];
	else [app downloadFinished];
	
}



@end